<template>
  <div class="page-container">
    <ShowList 
      :title="title" 
      :columns="columns" 
      :tableData="tableData" 
      :operation="operation" 
      :total="total"
      :pageNum="queryParams.pageNum"
      :pageSize="queryParams.pageSize"
      @refresh="handleRefresh"
      @page-change="handlePageChange"
      @delete="handleDelete"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import useUserStore from '@/store/modules/user'
import ShowList from '@/components/ncpsy/ZSPT/Page123Vue/ShowList.vue'
import { listProduct, delProduct } from '@/api/ncpsy/management/product'
import { ElMessage, ElMessageBox } from 'element-plus'

const userStore = useUserStore()
const title = ref('农产品列表')
const columns = ref([
  { prop: 'cropName', label: '作物名称', width: '180px', align: 'center' },
  { prop: 'status', label: '状态', width: '120px', align: 'center' },
  { prop: 'plantingAravage', label: '种植面积', width: '150px', align: 'center' },
  { prop: 'beginTime', label: '开始时间', width: '150px', align: 'center' },
  { prop: 'reapTime', label: '结束时间', width: '150px', align: 'center' },
  { prop: 'estimatedTotalYield', label: '预计产量', width: '150px', align: 'center' }
])
const operation = ref([
  { label: '完善档案', action: 'completeArchive', type: 'primary' },
  { label: '查看事件', action: 'recordEventbyCropId', type: 'success' }
])
const tableData = ref([])
const total = ref(0)
// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  userId: userStore.id
})

// 加载农产品数据
const loadProductData = async () => {
  try {
    console.log('加载农产品数据参数:', queryParams.value)
    const response = await listProduct(queryParams.value)
    tableData.value = response.rows || []
    total.value = response.total || 0
  } catch (error) {
    console.error('加载农产品数据失败:', error)
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadProductData()
})

const handleAdd = () => {
  console.log('添加按钮点击')
  // 这里添加处理逻辑
}

// 处理刷新事件
const handleRefresh = () => {
  queryParams.value.pageNum = 1
  loadProductData()
}

// 处理分页变化
const handlePageChange = (page) => {
  queryParams.value.pageNum = page
  loadProductData()
}

const handleEdit = ({ index, row }) => {
  console.log('修改按钮点击', index, row)
  // 这里添加处理逻辑
}

const handleDelete = async ({ index, row }) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该农产品信息吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await delProduct(row.cropId)
    ElMessage.success('删除成功')
    loadProductData() // 重新加载数据
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + (error.message || '未知错误'))
    }
  }
}
</script>

<style scoped>
.page-container {
  padding: 2px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}
</style>